package utils

import (
	"crypto/md5"
	"encoding/hex"
	"math/rand"
	"regexp"
	"time"
)

// 生成32位MD5
func MD5(text string) string {
	ctx := md5.New()
	ctx.Write([]byte(text))
	return hex.EncodeToString(ctx.Sum(nil))
}

//验证手机号
func IsMobile(mobile string) bool {
	match, _ := regexp.MatchString("^1[0-9]{10}$", mobile)
	return match
}

// 验证邮箱
func IsEmail(email string) bool {
	match, _ := regexp.MatchString("^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$", email)
	return match
}

// 验证数字、字母
func IsAlphanumeric(st string) bool {
	match, _ := regexp.MatchString("^[A-Za-z0-9]+$", st)
	return match
}

// 校验密码
func IsPassword(st string) bool {
	match, _ := regexp.MatchString("^[0-9a-zA-Z]{8,20}$", st)
	return match
}

//生成随机字符串
func GetRandomString(length int) string {
	str := "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
	bytes := []byte(str)
	result := []byte{}
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	for i := 0; i < length; i++ {
		result = append(result, bytes[r.Intn(len(bytes))])
	}
	return string(result)
}